<script setup>
import { Refresh } from "@element-plus/icons-vue";
import dayjs from "dayjs";
const { getNetworkInterfaces, setMacAddress } = window.electron;

const loading = ref(false);

// 本机网卡表格相关参数
const onlyMac = ref(true);
const onlyIpv4 = ref(true);
const networkData = ref([]);
const tableRef = ref(null);
const tableData = computed(() => {
  return networkData.value.reduce((result, item) => {
    const { mac, family } = item;
    // 判断是否仅查看Ipv4
    if (onlyIpv4.value && family !== "IPv4") return result;
    // 判断是否仅查看有效Mac
    if (onlyMac.value && mac === "00:00:00:00:00:00") return result;
    result.push(item);
    return result;
  }, []);
});
const tableSelectRow = ref(null);

// 修改mac地址相关参数
const newMac = ref(null);
const newMacApplyDateTime = ref(localStorage.getItem("newMacApplyDateTime") ?? null);
const newMacIntervalDay = computed(() => {
  if (!newMacApplyDateTime.value) return 0;
  const last = dayjs(dayjs(newMacApplyDateTime.value).format("YYYY-MM-DD"));
  const now = dayjs(dayjs().format("YYYY-MM-DD"));
  // 计算两个日期之间的天数差
  return now.diff(last, "day");
});

// 温馨提示
const tips = [
  "1. Mac地址修改应用时会短暂的网络断开, 耐心等待重连即可",
  "2. 支持记忆上次修改Mac的时间以及距今间隔天数, 小于12天颜色标绿, 大于12天颜色会标红",
  "3. 禁行规则: 12日内同一个设备最多上7个账号进行JJC, 否则禁止在该设备上登录的账号进入竞技场",
  "4. 遇事不决就打奶, 打奶永远是竞技场里最浪漫的事",
];

// 获取本机网卡表格数据信息
const getTableData = () => {
  const body = getNetworkInterfaces();
  networkData.value = Object.keys(body).reduce((result, key) => {
    const value = body[key].map((item) => ({ ...item, key }));
    // 以太网, WLAN排前面
    if (["以太网", "WLAN"].includes(key)) {
      result.unshift(...value);
    } else {
      result.push(...value);
    }
    return result;
  }, []);
  console.log("网卡信息: ");
  console.log(networkData.value);
};
// 刷新
const refresh = () => {
  document.location.reload();
};
// 表格勾选
const handleTableSelect = (list) => {
  const row = list.at(-1);
  if (row) {
    tableRef.value.clearSelection(); // 清空所有选择
    tableRef.value.toggleRowSelection(row, true); // 重新选择这一行
    tableSelectRow.value = row;
  } else {
    tableSelectRow.value = null;
  }
};
// 表格头样式
const handleHeaderCellClassName = ({ columnIndex }) => {
  if (columnIndex === 0) return "isHidden";
};
// 生成Mac地址
const generateMac = () => {
  /**
   * @description: 方法一
   */
  // const hexDigits = "0123456789abcdef";
  // let macAddress = [];
  // // 生成前三个字节，保证第一个字节的第一位是0或1
  // macAddress.push(
  //   hexDigits.charAt(Math.round(Math.random())) +
  //     hexDigits.charAt(Math.round(Math.random())) +
  //     ":" +
  //     hexDigits.charAt(Math.round(Math.random())) +
  //     hexDigits.charAt(Math.round(Math.random())) +
  //     ":" +
  //     hexDigits.charAt(Math.round(Math.random())) +
  //     hexDigits.charAt(Math.round(Math.random()))
  // );
  // // 生成后三个字节
  // macAddress.push(
  //   hexDigits.charAt(Math.round(Math.random())) +
  //     hexDigits.charAt(Math.round(Math.random())) +
  //     ":" +
  //     hexDigits.charAt(Math.round(Math.random())) +
  //     hexDigits.charAt(Math.round(Math.random())) +
  //     ":" +
  //     hexDigits.charAt(Math.round(Math.random())) +
  //     hexDigits.charAt(Math.round(Math.random()))
  // );
  // newMac.value = macAddress.join(":");

  /**
   * @description: 方法二
   */
  const format = "xy:xy:xy:xy:xy:xy";
  let d = new Date().getTime();
  if (window.performance && typeof window.performance.now === "function") {
    d += performance.now(); //use high-precision timer if available
  }
  newMac.value = format.replace(/[xy]/g, (c) => {
    var r = (d + Math.random() * 16) % 16 | 0;
    d = Math.floor(d / 16);
    return (c == "x" ? r : (r & 0x3) | 0x8).toString(16);
  });
};
// 应用Mac地址
const applyMac = async () => {
  if (!tableSelectRow.value) return ElMessage.error("oi~小鬼, 请先选择好要修改的网卡");

  // 1. Mac地址格式校验
  const rule = /[A-Fa-f0-9]{2}:[A-Fa-f0-9]{2}:[A-Fa-f0-9]{2}:[A-Fa-f0-9]{2}:[A-Fa-f0-9]{2}:[A-Fa-f0-9]{2}/;
  const macAry = newMac.value?.split(":");
  if (!rule.test(newMac.value) || macAry.length !== 6 || macAry.filter((item) => item.length !== 2).length) {
    return ElMessage.error("Mac地址格式错误,请自行检查或重新生成");
  }
  // 2. 修改本地Mac, 更新时间, 存储于本地
  try {
    loading.value = true;
    await setMacAddress(tableSelectRow.value.key, newMac.value);
    setTimeout(() => {
      newMacApplyDateTime.value = dayjs().format("YYYY-MM-DD HH:mm:ss");
      localStorage.setItem("newMacApplyDateTime", newMacApplyDateTime.value);
      ElMessage.success("应用成功");
      getTableData();
      loading.value = false;
    }, 10 * 1000);
  } catch (error) {
    console.error(error);
    ElMessage.error("应用失败");
    loading.value = false;
  }
};

onMounted(() => {
  getTableData();
});
</script>

<template>
  <div
    id="Home"
    v-loading="loading"
    element-loading-text="正在修改中..."
  >
    <!-- 表格: 当前网卡信息 -->
    <div class="title-box">
      <div class="title">
        <span>网卡信息检测</span>
        <el-icon
          class="refresh"
          title="刷新"
          @click="refresh"
          ><Refresh
        /></el-icon>
      </div>
      <!-- 是否仅查看有效Mac网卡信息 -->
      <div class="only-show">
        <el-checkbox
          v-model="onlyMac"
          label="仅有效Mac"
          size="small"
        />
        <el-checkbox
          v-model="onlyIpv4"
          label="仅IPv4"
          size="small"
        />
      </div>
    </div>
    <el-table
      ref="tableRef"
      border
      max-height="240"
      :data="tableData"
      :header-cell-class-name="handleHeaderCellClassName"
      @select="handleTableSelect"
    >
      <el-table-column
        type="selection"
        width="42"
      />
      <el-table-column
        label="网卡类别"
        prop="key"
        width="82"
        show-overflow-tooltip
      />
      <el-table-column
        label="协议"
        prop="family"
        width="60"
        show-overflow-tooltip
      />
      <el-table-column
        label="Mac地址"
        prop="mac"
        width="150"
        show-overflow-tooltip
      />
      <el-table-column
        label="IP地址"
        prop="address"
        width="120"
        show-overflow-tooltip
      />
      <el-table-column
        label="子网掩码"
        prop="netmask"
        width="120"
        show-overflow-tooltip
      />
      <el-table-column
        label="内部接口"
        prop="internal"
        width="82"
        show-overflow-tooltip
      >
        <template #default="scope">
          <span v-if="scope.row.internal">是</span>
          <span v-else>否</span>
        </template>
      </el-table-column>
      <el-table-column
        label="CIDR"
        prop="cidr"
        show-overflow-tooltip
      />
    </el-table>
    <el-divider />
    <!-- 操作: 修改网卡Mac地址 -->
    <div class="title-box">
      <div class="title">
        <span>修改Mac地址</span>
        <div class="mac-log-info">
          <div style="margin: 0 10px">
            <span class="label">修改时间: </span>
            <span class="value">{{ newMacApplyDateTime ?? "暂无修改记录" }}</span>
          </div>
          <div>
            <span class="label">相隔天数: </span>
            <span
              class="value"
              :style="{
                color: newMacIntervalDay < 12 ? 'var(--el-color-success)' : 'var(--el-color-danger)',
              }"
              >{{ newMacIntervalDay }}天</span
            >
          </div>
        </div>
      </div>
    </div>
    <div class="mac-generate">
      <el-input v-model="newMac" />
      <el-button @click="generateMac">随机生成</el-button>
      <el-button
        type="primary"
        @click="applyMac"
        >立即应用</el-button
      >
    </div>
    <el-divider />
    <!-- 温馨提示 -->
    <div class="title-box">
      <div class="title">
        <span>温馨提示</span>
      </div>
    </div>
    <div class="tips">
      <el-text
        v-for="(text, index) in tips"
        :key="index"
        type="info"
        >{{ text }}</el-text
      >
    </div>
    <!-- 底部信息 -->
    <div class="footer">
      <el-text type="info">版本号: 3.0.0</el-text>
    </div>
  </div>
</template>

<style lang="scss" scoped>
#Home {
  width: 100vw;
  height: 100vh;
  padding: 10px;
  box-sizing: border-box;
  .title-box {
    display: flex;
    align-items: center;
    justify-content: space-between;
    .title {
      color: rgb(115.2, 117.6, 122.4);
      font-size: 16px;
      font-weight: bold;
      padding-left: 4px;
      display: flex;
      align-items: center;
      position: relative;
      &::before {
        content: "";
        width: 4px;
        height: 100%;
        background-color: var(--el-text-color-regular);
        position: absolute;
        left: -2px;
      }
      .refresh {
        cursor: pointer;
        margin-top: 2px;
        margin-left: 10px;
        transition: 0.25s;
        :hover {
          color: #409eff;
        }
      }
      .mac-log-info {
        font-size: 12px;
        display: flex;
        color: rgb(115.2, 117.6, 122.4);
        .label {
          margin-right: 4px;
        }
      }
    }
    .only-show {
      .el-checkbox {
        margin-right: 10px;
      }
    }
  }
  .el-table {
    margin: 10px 0;
    margin-bottom: 20px;
    :deep(.isHidden) {
      .el-checkbox {
        visibility: hidden;
      }
    }
  }
  .mac-generate {
    display: flex;
    align-items: center;
    margin-top: 10px;
    font-size: 14px;
    .el-input {
      // width: 200px;
      margin-right: 10px;
    }
    .log {
      margin-left: 10px;
    }
  }
  .tips {
    margin-top: 10px;
    .el-text {
      display: block;
      font-size: 12px;
    }
  }
  .footer {
    position: fixed;
    left: 0;
    bottom: 0;
    width: 100%;
    height: 18px;
    display: flex;
    justify-content: end;
    .el-text {
      font-size: 12px;
      margin-right: 6px;
    }
  }
}
</style>
